package com.clstu.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 这是一个通过反射机制构造对象的探究
 */
public class ReflectInstance {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //1.得到user的class对象
        Class<?> userCls = Class.forName("com.clstu.reflection.User");

        //2.通过无参构造器创建对象
        Constructor<?> constructor = userCls.getConstructor();//得到无参构造器
        Object o = constructor.newInstance();
        System.out.println(o);

        //3.通过有参构造器创建对象
        Constructor<?> constructor1 = userCls.getConstructor(String.class);//得到的是有参构造器
        Object o2 = constructor1.newInstance("玛卡巴卡");
        System.out.println(o2);
        //4.通过非public的构造器创建对象
//        Constructor<?> constructor2 = userCls.getConstructor(int.class, String.class);//这句话会报错
                                                                     //这个方法只能得到public的构造器,
        Constructor<?> declaredConstructor = userCls.getDeclaredConstructor(int.class,String.class);//可以这样得到私有构造器
        declaredConstructor.setAccessible(true);//设置方法可以访问,(爆破),需要记住这个知识点,(可以当做访问私有方法的一种技巧)
        Object o3 = declaredConstructor.newInstance(20, "龙少");//直接这样也会报错,需要先爆破,这是私有方法
        System.out.println(o3);
    }
}
class User{
    private int age=10;
    private String name="along";

    public User(){}

    public User(String name){
        this.name = name;
    }

    private User (int age , String name ){
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}